﻿using System;
using System.Linq;
using System.Windows;
//using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using CircleDrawer;
using System.Windows.Controls;
using System.IO;
using Microsoft.Win32;

namespace ShapeDrawer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// marto e guz
    public partial class MainWindow : Window
    {
        public Toolbar toolbar;

        public MainWindow()
        {
            InitializeComponent();

            DirectoryInfo info = new DirectoryInfo("../");
            foreach (FileInfo file in info.GetFiles())
            {
                file.Delete();
            }

            toolbar = new Toolbar();
            this.LayoutGrid.Children.Add(toolbar);

            Uri logoUri = new Uri(@"..\..\Resources\temporaryLogo4.png", UriKind.Relative);
            ImageBrush brush = new ImageBrush();
            brush.ImageSource = new BitmapImage(logoUri);
            Rectangle logo = new Rectangle();
            logo.Fill = brush;
            logo.Width = 40;
            logo.Height = 32;

            this.MenuPanel.Children.Add(logo);
            this.scvDrawingPanel.ScrollChanged += scvDrawingPanel_ScrollChanged;

            CreateMenuIcons();
        }

        void scvDrawingPanel_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e.ExtentHeightChange != 0 | e.ExtentWidthChange != 0)
            {
                Point mousePosition = Mouse.GetPosition(scvDrawingPanel);
                Double offsetx = e.HorizontalOffset + mousePosition.X;
                Double offsety = e.VerticalOffset + mousePosition.Y;
                Double oldExtentWidth = e.ExtentWidth - e.ExtentWidthChange;
                Double oldExtentHeight = e.ExtentHeight - e.ExtentHeightChange;

                Double relx = offsetx / oldExtentWidth;
                Double rely = offsety / oldExtentHeight;

                offsetx = Math.Max(relx * e.ExtentWidth - mousePosition.X, 0);
                if (mousePosition.X > relx * e.ExtentWidth)
                {
                    Console.Out.WriteLine("Horizontal cut-off reached");
                }
                offsety = Math.Max(rely * e.ExtentHeight - mousePosition.Y, 0);
                if (mousePosition.Y > rely * e.ExtentHeight)
                {
                    Console.Out.WriteLine("Vertical cut-off reached");
                }
                this.scvDrawingPanel.ScrollToHorizontalOffset(offsetx);
                this.scvDrawingPanel.ScrollToVerticalOffset(offsety);
            }
        }
  
        private void CreateMenuIcons()
        {
            Icon newFileIcon = IconMaker.MakeNewFileIcon();
            newFileIcon.Frame.MouseLeftButtonUp += NewFileMouseClick;
            this.MenuPanel.Children.Add(newFileIcon.Frame);

            Icon openFileIcon = IconMaker.MakeOpenFileIcon();
            openFileIcon.Frame.MouseLeftButtonUp += OpenFileMouseClick;
            this.MenuPanel.Children.Add(openFileIcon.Frame);

            Icon saveIcon = IconMaker.MakeSaveIcon();
            saveIcon.Frame.MouseLeftButtonUp += SaveMouseClick;
            this.MenuPanel.Children.Add(saveIcon.Frame);
        }

        void OpenFileMouseClick(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";

            bool? clickedYes = openDialog.ShowDialog();

            if (clickedYes == true)
            {
                FileStream opener = new FileStream(openDialog.FileName, FileMode.Open);
                byte[] fileBytes = new byte[opener.Length];
                opener.Read(fileBytes, 0, (int)opener.Length);
                opener.Close();

                string filePath = "../openedFile" + openDialog.GetHashCode().ToString() + ".png";
                FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate);
                stream.Write(fileBytes, 0, fileBytes.Length);
                stream.Close();

                System.Drawing.Image img = System.Drawing.Image.FromFile(filePath);
                
                Image image = new Image();
                image.Source = new ImageSourceConverter().ConvertFromString(filePath) as ImageSource;
                image.Width = img.Width;
                image.Height = img.Height;
                image.Stretch = Stretch.Fill;

                DrawingPane drawingPane = new DrawingPane(img.Size.Width, img.Size.Height);
                
                drawingPane.Children.Add(image);

                this.scvDrawingPanel.Content = drawingPane;
            }
        }

        void NewFileMouseClick(object sender, MouseButtonEventArgs e)
        {
            NewFileWindow newFileWindow = new NewFileWindow();
            newFileWindow.ShowDialog();

            bool? result = newFileWindow.DialogResult;
            if (result == true)
            {
                int width = newFileWindow.Width;
                int height = newFileWindow.Height;
                DrawingPane drawingPane = new DrawingPane(width, height);

                this.scvDrawingPanel.Content = drawingPane;
            }
        }

        void SaveMouseClick(object sender, MouseButtonEventArgs e)
        {
            DrawingPane pane = scvDrawingPanel.Content as DrawingPane;

            if (pane == null)
            {
                return;
            }

            if (!pane.IsSaved)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
                bool? dialogResult = saveFileDialog.ShowDialog();

                if (dialogResult == true)
                {
                    Uri fileLocation = new Uri(saveFileDialog.FileName, UriKind.Absolute);
                    pane.MarkAsSaved(fileLocation);
                    PngUtils.SaveToPng(pane.SavedAtUri, pane.Clone());
                    
                    //ToChange:
                    MessageBox.Show("Saved to: " + saveFileDialog.FileName);
                }
            }
            else
            {
                PngUtils.SaveToPng(pane.SavedAtUri, pane.Clone());
            }
        }
    }
}
